package top.codef.gsonsupport;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import top.codef.properties.MercuryGsonProperties;

public class LocalDateTimeGsonAdapter extends TypeAdapter<LocalDateTime> {

	private final MercuryGsonProperties mercuryGsonProperties;

	public LocalDateTimeGsonAdapter(MercuryGsonProperties mercuryGsonProperties) {
		this.mercuryGsonProperties = mercuryGsonProperties;
	}

	@Override
	public void write(JsonWriter out, LocalDateTime value) throws IOException {
		if (value == null) {
			out.nullValue();
			return;
		}
		DateTimeFormatter dateTimeFormatter = confirmDatetimeFormatter();
		out.value(dateTimeFormatter.format(value));
	}

	@Override
	public LocalDateTime read(JsonReader in) throws IOException {
		String datetime = in.nextString();
		if (datetime == null)
			return null;
		DateTimeFormatter dateTimeFormatter = confirmDatetimeFormatter();
		LocalDateTime localDateTime = dateTimeFormatter.parse(datetime, LocalDateTime::from);
		return localDateTime;
	}

	private DateTimeFormatter confirmDatetimeFormatter() {
		String pattern = mercuryGsonProperties.getDatetimePattern();
		DateTimeFormatter dateTimeFormatter = pattern != null ? DateTimeFormatter.ofPattern(pattern)
				: mercuryGsonProperties.getDateTimeFormat().getDateTimeFormatter();
		return dateTimeFormatter;
	}
}
